package com.baijing.springbootstarterdata.service.impl;

import com.baijing.springbootstarterdata.dao.PersonRepository;
import com.baijing.springbootstarterdata.domain.Person;
import com.baijing.springbootstarterdata.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;


@Service
public class DemoServiceImpl implements DemoService {
    @Autowired
    private PersonRepository personRepository;

    @Override
    @Transactional(rollbackFor = {IllegalArgumentException.class})
    public Person savePersonWithRollBack(Person person) {
        Person p = personRepository.save(person);
        if (person.getName().equals("baijing")) {
            throw new IllegalArgumentException("baijing 已存在，数据将回滚");
        }
        return p;

    }

    @Override
    @Transactional(noRollbackFor = {IllegalArgumentException.class})
    public Person savePersonWithoutRollBack(Person person) {
        Person p = personRepository.save(person);
        if (person.getName().equals("baijing")) {
            throw new IllegalArgumentException("baijing 已存在，数据不回滚");
        }
        return p;

    }

    @Override
    @CachePut(value = "people", key = "#person.id")
    public Person save(Person person) {
        Person p = personRepository.save(person);
        System.out.println("为id：" + person.getId() + "做了缓存.save.");
        return p;
    }

    @Override
    @CacheEvict(value = "people", key = "#id")
    public void remove(Long id) {
        System.out.println("为id: " + id + "删除缓存.");
        personRepository.deleteById(id);
    }

    @Override
    @Cacheable(value = "people", key = "#person.id")
    public Person findOne(Person person) {
        Person p = personRepository.findOne(Example.of(person)).orElse(new Person());
        System.out.println("为id：" + person.getId() + "做了缓存,findone.");
        return p;
    }
}
